package com.winchain.provider;

import com.shell.bee.base.utils.DateUtil;
import com.shell.bee.base.utils.SpringContextUtil;
import com.shell.bee.base.utils.SystemUtil;
import com.shell.bee.persistence.transaction.Transaction;
import com.shell.bee.persistence.transaction.TransactionUtil;
import com.shell.framework.utils.CommonDataUtil;
import com.shell.framework.utils.MessageSender;
import com.shell.framework.utils.SysDateUtil;
import com.shell.governor.modules.message.keyword.PrepymtBatchKeyword;
import com.winchain.basic.exception.ExtException;
import com.winchain.chainbill.bill.base.po.CbOpt;
import com.winchain.chainbill.bill.base.po.CbRec;
import com.winchain.chainbill.bill.base.service.CbOptService;
import com.winchain.chainbill.bill.base.service.CbRecService;
import com.winchain.chainbill.bill.biz.query.vo.CbRecVo;
import java.math.BigDecimal;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class PrepaymentExtProvider {
	@Autowired
	private CbRecService cbRecService;
	@Autowired
	private CbOptService cbOptService;
	private Log logger = LogFactory.getLog(getClass());

	@RequestMapping({ "/prepayment/batchJob" })
	public void prepaymentBatchJob(@RequestParam("workDate") String workDate) {
		this.logger.info("--------PrepaymentBatchJob excute start--------");
		try {
			boolean exFlag = false;
			int successNo = 0;

			String billState = "S032";
			List<CbRecVo> cbRecList = this.cbRecService.selectBillForPrepayment(workDate, billState);
			this.logger.info("message size is " + cbRecList.size());
			for (final CbRecVo cbRec : cbRecList) {
				try {
					TransactionUtil.execute(new Transaction() {
						public void doInTransaction() {
							PrepaymentExtProvider.this.billMove(cbRec);
						}
					}, new int[0]);

					boolean sendSuful = false;
					sendSuful = sendSysMessage(cbRec);
					if (sendSuful) {
						successNo += 1;
					} else {
						exFlag = true;
					}
				} catch (Exception e) {
					exFlag = true;
					e.printStackTrace();
					this.logger.error("PrepaymentBatchJob excute error!", e);
				}
			}
			this.logger.info("the value of exFlag is " + exFlag + " the value of successNo is " + successNo);
			if (exFlag) {
				throw new ExtException("��������������������������������������������");
			}
		} catch (Exception e) {
			e.printStackTrace();
			this.logger.error("������������������������", e);
			throw new ExtException(e.getMessage());
		}
		this.logger.info("--------PrepaymentBatchJob excute end--------");
	}

	private boolean sendSysMessage(CbRecVo cbRec) {
		boolean sendSuful = false;
		PrepymtBatchKeyword keyWord = getPrepymtBatchKeyword(cbRec);

		String templateId = "MT02608";
		try {
			MessageSender.sendMessageByTmpl("", templateId, keyWord, cbRec.getSellerId());
			sendSuful = true;
			this.logger.info("system message send successful, billCode is " + cbRec.getBillCode());
		} catch (Exception e) {
			e.printStackTrace();
			this.logger.error("������������������������������ ", e);
		}
		return sendSuful;
	}

	private boolean sendSMS(CbRecVo cbRec, boolean sdSYSFlag) {
		boolean sendSuful = false;
		PrepymtBatchKeyword smskeyWord = getPrepymtBatchKeyword(cbRec);
		String smsTemplateId = "MT02608";
		try {
			MessageSender.sendMessageByTmpl("", smsTemplateId, smskeyWord, cbRec.getSellerId());
			if (sdSYSFlag) {
				sendSuful = true;
			}
			this.logger.info("phone message send successful, billCode is " + cbRec.getBillCode());
		} catch (Exception se) {
			se.printStackTrace();
			this.logger.error("�������������������������� ", se);
		}
		return sendSuful;
	}

	private PrepymtBatchKeyword getPrepymtBatchKeyword(CbRecVo cbRec) {
		PrepymtBatchKeyword keyWord = new PrepymtBatchKeyword();
		keyWord.setBuyerNm(cbRec.getBuyerNm());
		BigDecimal billAmt = cbRec.getBillAmt();

		keyWord.setBillAmt(billAmt.toString());
		String expDate = SysDateUtil.parseDate(cbRec.getExpDate(), "yyyyMMdd", "yyyy-MM-dd");
		String sndDate = SysDateUtil.parseDate(cbRec.getSndDate(), "yyyyMMdd", "yyyy-MM-dd");
		keyWord.setExpDate(expDate);
		keyWord.setSndDate(sndDate);
		keyWord.setWebsite(SpringContextUtil.getProperty("chainbill.website"));

		return keyWord;
	}

	private void billMove(CbRecVo cbRec) {
		CbRec bill = (CbRec) this.cbRecService.selectByKey(cbRec.getBillId());
		String curState = null;
		int optSeq = bill.getOptSeq().intValue() + 1;
		bill.setOptSeq(Integer.valueOf(optSeq));
		if ("S023".equals(cbRec.getBillState())) {
			curState = "S023";
		} else if ("S032".equals(cbRec.getBillState())) {
			curState = "S032";
		}
		bill.setCurBillState(curState);
		bill.setBillState("S003");
		int affectedRows = this.cbRecService.updateBillOptimistically(bill);
		if (affectedRows != 1) {
			throw new ExtException("����������������������");
		}
		CbOpt opt = new CbOpt();
		opt.setOptCode("EX09");
		opt.setCurState(curState);
		opt.setNxtState("S003");
		opt.setRemark("�������� ��������");
		opt.setOptId(SystemUtil.getUUID());
		opt.setBillId(bill.getBillId());
		opt.setOptSeq(Integer.valueOf(optSeq));
		opt.setOprId(CommonDataUtil.getUserId());
		opt.setOptTime(DateUtil.getSystemDateTime());
		this.cbOptService.save(opt);
	}
}
